<?php
/**
 * 辅助函数文件
 */

// JWT Token生成和验证
function generateToken($payload) {
    require_once __DIR__ . '/../config/config.php';
    
    $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
    $payload['exp'] = time() + $appConfig['token_expire'];
    $payload = json_encode($payload);
    
    $base64Header = base64_encode($header);
    $base64Payload = base64_encode($payload);
    
    $signature = hash_hmac('sha256', "$base64Header.$base64Payload", $appConfig['secret_key'], true);
    $base64Signature = base64_encode($signature);
    
    return "$base64Header.$base64Payload.$base64Signature";
}

function verifyToken($token) {
    require_once __DIR__ . '/../config/config.php';
    
    $parts = explode('.', $token);
    if (count($parts) !== 3) {
        return false;
    }
    
    list($base64Header, $base64Payload, $base64Signature) = $parts;
    
    $signature = base64_decode($base64Signature);
    $expectedSignature = hash_hmac('sha256', "$base64Header.$base64Payload", $appConfig['secret_key'], true);
    
    if (!hash_equals($signature, $expectedSignature)) {
        return false;
    }
    
    $payload = json_decode(base64_decode($base64Payload), true);
    
    if (isset($payload['exp']) && $payload['exp'] < time()) {
        return false;
    }
    
    return $payload;
}

// 密码加密和验证
function hashPassword($password) {
    return password_hash($password, PASSWORD_DEFAULT);
}

function verifyPassword($password, $hash) {
    return password_verify($password, $hash);
}

// 输入过滤
function sanitizeInput($input) {
    if (is_array($input)) {
        return array_map('sanitizeInput', $input);
    }
    
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

// 验证手机号格式
function isValidPhone($phone) {
    return preg_match('/^1[3-9]\d{9}$/', $phone);
}

// 生成随机字符串
function generateRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    
    return $randomString;
}

// 文件上传处理
function handleFileUpload($file, $allowedTypes = [], $maxSize = 5242880) {
    require_once __DIR__ . '/../config/config.php';
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('文件上传失败');
    }
    
    if ($file['size'] > $maxSize) {
        throw new Exception('文件大小超过限制');
    }
    
    $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!empty($allowedTypes) && !in_array($fileExtension, $allowedTypes)) {
        throw new Exception('不支持的文件类型');
    }
    
    // 创建上传目录
    if (!is_dir($appConfig['upload_path'])) {
        mkdir($appConfig['upload_path'], 0755, true);
    }
    
    $fileName = uniqid() . '.' . $fileExtension;
    $filePath = $appConfig['upload_path'] . $fileName;
    
    if (!move_uploaded_file($file['tmp_name'], $filePath)) {
        throw new Exception('文件保存失败');
    }
    
    return '/uploads/' . $fileName;
}

// 获取客户端IP
function getClientIP() {
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    
    return $ip;
}

// 记录日志
function logMessage($message, $level = 'INFO') {
    $logFile = __DIR__ . '/../logs/app.log';
    $logDir = dirname($logFile);
    
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    $timestamp = date('Y-m-d H:i:s');
    $logMessage = "[$timestamp] [$level] $message\n";
    
    file_put_contents($logFile, $logMessage, FILE_APPEND | LOCK_EX);
}

?>